/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ebookmgr;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.JProgressBar;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.TreeModel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableColumn;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 *
 * @author mazhao
 */
public class ImportDialog extends JDialog {

    // the most import data to export
    //
    // {
    //   from path => to path,
    //   from path => to path
    // }
    private Map<String, String> fromTo = null;
    private final JTextField importTxt = new JTextField();
    private final JProgressBar pb = new JProgressBar();
    private final JButton cancelBtn = new JButton(Configuration.getUIString("ImportDialog.Cancel"));
    private final JButton okBtn = new JButton(Configuration.getUIString("ImportDialog.Ok"));
    private final JRadioButton moverb = new JRadioButton(Configuration.getUIString("ImportDialog.MoveTo"), false);
    private final JRadioButton copyrb = new JRadioButton(Configuration.getUIString("ImportDialog.CopyTo"), true);
    private final JTable mainTable = new JTable();
    private final JScrollPane scrollPane = new JScrollPane(mainTable);
    
    public ImportDialog(JFrame parent, boolean model) {

        super(parent, model);


        this.setTitle(Configuration.getUIString("ImportDialog.Title"));
        this.setSize(new Dimension(600, 400));

        this.setLocation(EBookMgrUtil.getProperPosition(parent, this));

        this.setLayout(new BorderLayout());

        JPanel topPanel = new JPanel();

        topPanel.setLayout(new BorderLayout());
        JLabel importLbl = new JLabel(Configuration.getUIString("ImportDialog.Import"));

        importTxt.setEditable(false);
        JButton importBtn = new JButton(Configuration.getUIString("ImportDialog.Choose"));

        topPanel.add(importLbl, BorderLayout.WEST);
        topPanel.add(importTxt, BorderLayout.CENTER);
        topPanel.add(importBtn, BorderLayout.EAST);

        this.add(topPanel, BorderLayout.NORTH);

        
        mainTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        final DefaultTableModel tm = new ImportTableModel();
        mainTable.setModel(tm);
        tm.addTableModelListener(new TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent e) {
                changeToFolder(e, tm);
            }
        });

        // for windows only! mac not support
        mainTable.setAutoCreateRowSorter(true);

        mainTable.setRowSelectionAllowed(true);
        mainTable.setColumnSelectionAllowed(true);

        
        this.add(scrollPane, BorderLayout.CENTER);

        // add input button click event.
        importBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                chooseClick(importTxt, mainTable);
            }
        });

        JPanel downPanel = new JPanel();
        downPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

        // Copy Type: move or copy

        ButtonGroup bg = new ButtonGroup();
        bg.add(moverb);
        bg.add(copyrb);
        JPanel copyTypePanel = new JPanel();
        copyTypePanel.add(moverb);
        copyTypePanel.add(copyrb);

        downPanel.add(copyTypePanel);

        pb.setMinimum(0);
        pb.setMaximum(100);
        pb.setSize(200, 20);


        cancelBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        });


        okBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // do import
                okClick();
            }
        });
        downPanel.add(pb);
        downPanel.add(cancelBtn);
        downPanel.add(okBtn);


        this.add(downPanel, BorderLayout.SOUTH);
    }

    private void changeToFolder(TableModelEvent e, DefaultTableModel tm) {

        int row = e.getFirstRow();
        int col = e.getColumn();
        int keyCol = col - 1;
        if (row >= 0 && col >= 1) {
            String key = (String) tm.getValueAt(row, keyCol);
            String value = (String) tm.getValueAt(row, col);
            fromTo.remove(importTxt.getText() + key);
            fromTo.put(importTxt.getText() + key, Configuration.getBaseFolderPath() + value);
        }

    }

    private void okClick() {

        int ret = JOptionPane.showConfirmDialog(this, Configuration.getUIString("ImportDialog.ImportConfirmMsg"));
        if (ret == JOptionPane.OK_OPTION) {
            // @TODO: add a new thread, when thread stop




            final Thread showThread = new Thread(new Runnable() {

                @Override
                @SuppressWarnings("static-access")
                public void run() {
                    while (true) {
                        pb.setValue((pb.getValue() + 5) % 100);
                        repaint();
                        System.out.println("set running value!");
                        try {
                            Thread.currentThread().sleep(1000);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            });


            Thread importThread = new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        cancelBtn.setEnabled(false);
                        okBtn.setEnabled(false);

                        if(moverb.isSelected()) {
                            ImportUtil.importFiles(fromTo, true);
                        } else {
                            ImportUtil.importFiles(fromTo, false);
                        }
                        
                        showThread.stop();
                        setVisible(false);

                        JOptionPane.showMessageDialog(getParent(), Configuration.getUIString("ImportDialog.ImportSuccessMsg"));
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(getParent(), Configuration.getUIString("ImportDialog.ImportFailedMsg") + ex.getMessage());
                    }
                }
            });

            showThread.start();
            importThread.start();

//            try {
//                showThread.join();
//                importThread.join();
//                Thread.currentThread().join();
//            } catch (InterruptedException ex) {
//                ex.printStackTrace();
//            }

        } else {
            JOptionPane.showMessageDialog(this, Configuration.getUIString("ImportDialog.ImportCancelMsg"));
        }

    }

    private void chooseClick(JTextField txt, JTable table) throws UnsupportedOperationException {
        // create, configure and show file chooser dialog.
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setMultiSelectionEnabled(false);

        int ret = fc.showOpenDialog(this);

        // if choose:
        if (ret == JFileChooser.APPROVE_OPTION) {
            // set folder path
            File folder = fc.getSelectedFile();
            txt.setText(folder.getAbsolutePath());

            // list files to be import
            List<String> importFiles = ImportUtil.findFiles(folder.getAbsolutePath());

            // get main frame folder table model
            MainFrame mainFrame = (MainFrame) this.getParent();
            TreeModel tm = mainFrame.getCatalogTree().getModel();

            // get map files
            this.fromTo = ImportUtil.mapFiles(importFiles, tm, Configuration.getBaseFolderPath());

            // refresh table model
            DefaultTableModel mytm = (DefaultTableModel) table.getModel();

            Vector data = new Vector();
            Iterator<Entry<String, String>> it = fromTo.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, String> ent = it.next();
                Vector line = new Vector();
                line.add(ent.getKey().substring(txt.getText().length()));
                line.add(ent.getValue().substring(Configuration.getBaseFolderPath().length()));
                data.add(line);
            }

            Vector header = new Vector();
            header.add(Configuration.getUIString("ImportDialog.From"));
            header.add(Configuration.getUIString("ImportDialog.To"));
            mytm.setDataVector(data, header);

            TableColumn colFrom = table.getColumnModel().getColumn(0);
            colFrom.setPreferredWidth(300);

            TableColumn colTo = table.getColumnModel().getColumn(1);

            JComboBox combox = new JComboBox();
            DefaultMutableTreeNode root = (DefaultMutableTreeNode) mainFrame.getCatalogTree().getModel().getRoot();
            Iterator<String> pathItems = ImportUtil.parseTreeModel(root).keySet().iterator();
            while (pathItems.hasNext()) {
                combox.addItem(pathItems.next());
            }
            colTo.setCellEditor(new DefaultCellEditor(combox));

            colTo.setPreferredWidth(300);

            // repaint table
            table.repaint();
        }
    }
    public void reset() {
        this.importTxt.setText("");
        this.fromTo = null;
        this.mainTable.setModel(new ImportTableModel() );

        this.setSize(new Dimension(600, 400));
         this.pack();
    }
}

class ImportTableModel extends DefaultTableModel {

    @Override
    public boolean isCellEditable(int row, int column) {
        if (column == 0) {
            return false;
        } else {
            return true;
        }
    }
}

